package com.ghd.dataviz.security.impl;

import com.ghd.dataviz.core.security.impl.UserDetailsImpl;
import com.ghd.dataviz.entity.User;
import com.ghd.dataviz.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author ：ghd
 * @date ：Created in 2020-03-15 15:31
 * @description：spring security 用户接口
 * @modified By：
 * @version: $
 */
@Slf4j
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    private final IUserService userService;

    public UserDetailsServiceImpl(IUserService userservice) {
        this.userService = userservice;
    }


    @Override
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
        UserDetails userDetails = null;

        User user = userService.findByName(name);
        if (user != null) {
            List<GrantedAuthority> authorities = new ArrayList<>();
            authorities.add(new SimpleGrantedAuthority("ADMIN"));
            //封装自定义UserDetails类
            userDetails = new UserDetailsImpl(user.getId(), user.getName(),
                    user.getPassword(), authorities);
        }
        return userDetails;
    }
}
